import { service, crudParamsSerializer } from '@/utils/request'
import { CreateQueryParams } from '@nestjsx/crud-request'
import { Score } from './score.dto'
import { CrudPaginatedRes } from '..'
import * as _ from 'lodash'

export const defaultScoreData: Partial<Score> = {
  tag: ''
}

export function getScores (params?: CreateQueryParams) {
  return service.get<Score[] | CrudPaginatedRes<Score>>(
    '/resources/scores',
    {
      params,
      paramsSerializer: crudParamsSerializer
    }
  )
}

export function getScoreById (id: number | string, params?: CreateQueryParams) {
  return service.get<Score>(
    `/resources/scores/${id}`,
    {
      params,
      paramsSerializer: crudParamsSerializer
    }
  )
}

export function createScore (dto: Partial<Score>, params?: CreateQueryParams) {
  const data = new FormData()
  _.forIn(dto, (value, key) => {
    if (key !== 'id' && value) {
      if (typeof value === 'string' || typeof value === 'number') {
        data.append(key, value.toString())
      } else if (value instanceof Blob) {
        data.append(key, value)
      } else if (value instanceof Date) {
        data.append(key, value.toISOString())
      } else {
        data.append(key, JSON.stringify(value))
      }
    }
  })
  return service.post<Score>(
    '/resources/scores',
    data,
    {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      params,
      paramsSerializer: crudParamsSerializer
    }
  )
}

export function updateScore (id: number | string, dto: Partial<Score>, params?: CreateQueryParams) {
  const data = new FormData()
  _.forIn(dto, (value, key) => {
    if (key !== 'id' && value) {
      if (typeof value === 'string' || typeof value === 'number') {
        data.append(key, value.toString())
      } else if (value instanceof Blob) {
        data.append(key, value)
      } else if (value instanceof Date) {
        data.append(key, value.toISOString())
      } else {
        data.append(key, JSON.stringify(value))
      }
    }
  })
  return service.patch<Score>(
    `/resources/scores/${id}`,
    data,
    {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      params,
      paramsSerializer: crudParamsSerializer
    }
  )
}

export function removeScore (id: number | string) {
  return service.request({
    url: `/resources/scores/${id}`,
    method: 'delete'
  })
}
